


import 'dart:ui';

import 'package:alip_app/AppStates/NetworkApi.dart';
import 'package:alip_app/Entities/GetTopicResult.dart';
import 'package:alip_app/Entities/TopicDetailsResult.dart';
import 'package:alip_app/StateManagement/ModelProvider.dart';
import 'package:alip_app/UI/Pages/TopicsPage.dart';
import 'package:alip_app/UI/Widgets/Dialogs.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart' as Intl;

class TopicDetailsPage extends StatefulWidget {
  final Topic topic;
  final String heroTag;

  TopicDetailsPage({this.topic, this.heroTag});
  @override
  State<StatefulWidget> createState() => _TopicDetailsPageState();
}

class _TopicDetailsPageState extends State<TopicDetailsPage> with AutomaticKeepAliveClientMixin {
  double get headerSize => MediaQuery.of(context).padding.top + 60;
  @override
  Widget build(BuildContext context) {
    super.build(context);

    Widget buildingWidget;

    final webApi = ModelContainer.of<NetworkApi>(context).model.api;
    buildingWidget = Scaffold(
      body: Stack(
        children: <Widget>[
          Positioned.fill(
            child: FutureBuilder<TopicDetailsResult>(
              future: webApi.getTopicDetails(topicId: this.widget.topic.topicId),
              builder: (context, snapshot) {
                if (snapshot.hasError) return Center(
                  child: Text("An error occurred while loading data, there is the error message:\n\n${snapshot.error}"),
                );
                if (snapshot.hasData) {
                  final topicDetails = snapshot.data.topic;
                  return ListView(
                      padding: EdgeInsets.all(10.0),
                      children: [
                        SizedBox(height: headerSize,),
                        Padding(padding: EdgeInsets.all(10.0), child: Text(topicDetails.title, textAlign: TextAlign.center, style: Theme.of(context).textTheme.headline6,),),
                        _buildBlurFrame(
                          child: buildAuthorHeader(context, userName: topicDetails.userNickName, userKind: topicDetails.userTitle, avatarUrl: topicDetails.icon, heroTag: this.widget.heroTag),
                        ),
                        Divider(),
                        SizedBox(height: 10.0,),
                        Padding(padding: EdgeInsets.symmetric(horizontal: 10.0), child: _buildBadges(context, snapshot.data),),
                        ...snapshot.data.topic.content.map((content) => _buildContentItem(content: content)).toList(),
                        Divider(),
                        Text("ئىنكاسلار (${snapshot.data.topic.replies})", style: Theme.of(context).textTheme.headline6,),
                        ..._buildReplays(snapshot.data),
                        SizedBox(height: 70.0,)
                      ]
                  );
                }
                return Center(
                  child: CircularProgressIndicator(),
                );
              },
            ),
          ),
          _buildTitle(),
          _buildReplayPanel(),
        ],
      ),
    );
    buildingWidget = Directionality(textDirection: TextDirection.rtl, child: buildingWidget);
    return buildingWidget;
  }

  Widget _buildContentItem({TopicContent content, enableBlurring = true}) {
    if (content.type == 0) {
      Widget textWidget = Text(content.infor,);
      return enableBlurring ? _buildBlurFrame(child: textWidget,) : Padding(padding: EdgeInsets.all(5.0), child: textWidget,);
    }
    if (content.type == 4) return _buildBlurFrame(
      child: Row(
        children: <Widget>[
          Expanded(child: Text(content.infor, style: TextStyle(color: Theme.of(context).primaryColor, decoration: TextDecoration.underline),),),
          Builder(
            builder: (context) => DropdownButton<int>(
              icon: Icon(Icons.more_horiz,),
              underline: SizedBox(),
              items: [
                DropdownMenuItem(child: Text("كۆچۈرۈش"), value: 0,),
                DropdownMenuItem(child: Text("تور كۆرگۈچتە ئېچىش",), value: 1,),
              ],
              onChanged: (value) {
                if (value == 0) {
                  Clipboard.setData(ClipboardData(text: content.url));
                  Scaffold.of(context).showSnackBar(SnackBar(content: Text("ئادېرىس كۆچۈرۈلدى!")));
                }
                if (value == 1) {
                  final result = Dialogs.showQuestionDialog(context, title: "ئەسكەرتىش", content: "بۇ ئادېرىسنى تور كۆرگۈچتە ئاچامسىز؟");
                }
              },
            ),
          ),
        ],
      ),
    );
    //content.type == 1 then this item is image.
    return _buildBlurFrame(
      child: ClipRRect(
        borderRadius: BorderRadius.circular(10.0),
        child: CachedNetworkImage(
          imageUrl: content.originalInfo ?? content.infor,
          progressIndicatorBuilder: (context, url, progress) => LinearProgressIndicator(value: progress.progress),
          errorWidget: (context, url, error) => Row(
            children: <Widget>[
              Icon(Icons.broken_image, color: Colors.red,),
              Expanded(child: Text("رەسىم يۈكلەش مەغلۇب بولدى!", style: TextStyle(color: Colors.red),),)
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildBlurFrame({Widget child}) {
    return Container(
      child: child,
      padding: EdgeInsets.all(8.0),
      margin: EdgeInsets.all(5.0),
      decoration: BoxDecoration(
        color: Theme.of(context).backgroundColor,
        borderRadius: BorderRadius.circular(15.0)
      ),
    );
  }

  Widget _buildBadges(BuildContext context, TopicDetailsResult topic) {
    final topicDetails = topic.topic;
    final colorsOfBadges = Theme.of(context).primaryColor;

    return IconTheme(data: IconThemeData(size: 14.0, color: colorsOfBadges), child: DefaultTextStyle(
      style: TextStyle(fontSize: 11.0, color: colorsOfBadges),
      child: Row(
        children: <Widget>[
          if (topicDetails.content.where((element) => element.type == 1).length > 0) ...[
            buildBadge(context, text: SizedBox(), icon: Icon(Icons.image)),
            SizedBox(width: 5.0,),
          ],
          buildBadge(context, icon: Icon(Icons.remove_red_eye), text: Text("${topicDetails.hits}")),
          SizedBox(width: 5.0,),
          buildBadge(context, icon: Icon(Icons.message), text: Text("${topicDetails.replies}")),
          buildBadge(context, icon: Icon(CupertinoIcons.tags_solid), text: Text(topic.forumName)),
          Spacer(),
          buildBadge(context, text: Text(Intl.DateFormat("yyyy-MM-dd HH-mm").format(DateTime.fromMillisecondsSinceEpoch(int.parse(topicDetails.createDate))), textDirection: TextDirection.ltr,), icon: Icon(Icons.timer))
        ],
      ),
    )
    );
  }

  List<Widget> _buildReplays(TopicDetailsResult topic) {
    final widgets = <Widget>[];
    for (final replay in topic.list) {
      widgets.addAll([
        _buildBlurFrame(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              buildAuthorHeader(context, userName: replay.replyName, avatarUrl: replay.icon, userKind: replay.userTitle),
              ...replay.replyContent.map((e) => _buildContentItem(content: e, enableBlurring: false))
            ],
          ),
        )
      ]);
    }
    return widgets;
  }

  Widget _buildTitle() {
    Widget buildingWidget = ClipRRect(
      child: BackdropFilter(
        filter: ImageFilter.blur(sigmaX: 20.0, sigmaY: 20.0),
        child: Container(
          color: Theme.of(context).backgroundColor,
          alignment: Alignment.bottomRight,
          child: Row(
            children: <Widget>[
              IconButton(icon: Icon(Icons.arrow_back_ios, color: Theme.of(context).primaryColor,), onPressed: (){
                Navigator.of(context).pop();
              })
            ],
          ),
        ),
      ),
    );

    buildingWidget = Positioned(
      child: buildingWidget,
      left: 0.0,
      right: 0.0,
      top: 0.0,
      height: this.headerSize,
    );
    return buildingWidget;
  }

  var expanded = false;
  Widget _buildReplayPanel() {
    Widget buildingWidget = ClipRRect(
      child: BackdropFilter(
        filter: ImageFilter.blur(sigmaY: 20.0, sigmaX: 20.0),
        child: StatefulBuilder(
          builder: (context, setState) => AnimatedContainer(
            duration: Duration(milliseconds: 600),
            curve: Curves.easeOutQuart,
            color: Theme.of(context).backgroundColor,
            width: double.infinity,
            height: expanded ? 150.0 : 60,
            child: Center(
              child: Container(
                constraints: BoxConstraints(maxWidth: 450.0),
                alignment: Alignment.center,
                padding: EdgeInsets.symmetric(vertical: 10.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    SizedBox(width: 10.0,),
                    CircleAvatar(backgroundColor: Theme.of(context).scaffoldBackgroundColor, child: IconButton(icon: Icon(CupertinoIcons.reply, color: Theme.of(context).hintColor,), onPressed: (){}),),
                    SizedBox(width: 10.0,),
                    Expanded(child: TextField(
                      decoration: InputDecoration(
                        contentPadding: EdgeInsets.all(8.0),
                        enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(10.0), borderSide: BorderSide(color: Theme.of(context).scaffoldBackgroundColor)),
                        focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(10.0), borderSide: BorderSide(color: Theme.of(context).scaffoldBackgroundColor)),
                        filled: true,
                        fillColor: Theme.of(context).scaffoldBackgroundColor,
                        prefixIcon: IconButton(icon: Icon(expanded ? Icons.keyboard_arrow_down : Icons.keyboard_arrow_up, color: Theme.of(context).hintColor,), onPressed: (){
                          expanded = !expanded;
                          setState(() {});
                        }),
                      ),
                      maxLines: 5,
                    )),
                    SizedBox(width: 10.0,),
                    CircleAvatar(backgroundColor: Theme.of(context).scaffoldBackgroundColor, child: IconButton(icon: Icon(Icons.more_horiz, color: Theme.of(context).hintColor,), onPressed: (){}),),
                    SizedBox(width: 10.0,),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
    buildingWidget = Align(
      alignment: Alignment.bottomCenter,
      child: buildingWidget,
    );
    return buildingWidget;
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

